package code.codeworld.common.kits;

import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 富文本工具
 * @Author: codeworld
 * @Date: 2023/10/23-16:22
 * @version: 1.0
 */
public class EditTextUtil {
    private static final Pattern pImage = Pattern.compile("<img.*src\\s*=\\s*(.*?)[^>]*?>", Pattern.CASE_INSENSITIVE);
    private static final Pattern rImage = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)");

    /**
     * 提取富文本中纯文本
     */
    public static String getText(String richText) {
        if (StringUtils.hasText(richText)) {
            String regx = "(<.+?>)|(</.+?>)";
            Matcher matcher = Pattern.compile(regx).matcher(richText);
            while (matcher.find()) {
                // 替换图片/空格？
                richText = matcher.replaceAll("").replace("&nbsp;", "");
            }
        }
        return richText;
    }

    /**
     * 提取富文本中图片地址
     */
    public static List<String> getImgStr(String richText) {
        List<String> list = new ArrayList<>();
        if (StringUtils.hasText(richText)) {
            Matcher pMatcher = pImage.matcher(richText);
            while (pMatcher.find()) {
                // 得到<img />数据
                String img = pMatcher.group();
                // 匹配<img>中的src数据
                Matcher rMatcher = rImage.matcher(img);
                while (rMatcher.find()) {
                    list.add(rMatcher.group(1));
                }
            }
        }
        return list;
    }

}
